<?php
/**
* @version   $Id: generate_image.php 9 2011-08-09 18:27:23Z simonpoghosyan@gmail.com $
* @package   Heat Map
* @copyright Copyright (C) 2008 - 2011 Edvard Ananyan, Simon Poghosyan. All rights reserved.
* @license   http://www.gnu.org/licenses/gpl.html GNU/GPL
*/

defined('_JEXEC') or die('Restricted access');

global $mainframe;

$type = JRequest::getVar('type', '', 'post', 'string');
$date1 = JRequest::getVar('date1', '', 'post', 'string');
$date2 = JRequest::getVar('date2', '', 'post', 'string');

if($type == 'create_stat' and $date1 != '' and $date2 != '') {
    // Including heatmap class
    include 'plugins/system/heatmap/class/Heatmap.class.php';
    include 'plugins/system/heatmap/class/HeatmapFromFile.class.php';

    $width = JRequest::getVar('screen_w', '', 'post', 'int');
    $height = JRequest::getVar('screen_h', '', 'post', 'int');
    

    $heatmap = new HeatmapFromFile();

    $heatmap->cache = 'cache';
    // Generated files
    $heatmap->path = 'cache';

    // Final file
    $img_secret = substr(md5($mainframe->getCfg('secret')),5,10);
    $heatmap->file = 'heatmap-'.$img_secret.'-%d.png';

    $db =& JFactory::getDBO();

    //get total count of clicks
    $query = "SELECT COUNT(`id`) FROM #__heatmap WHERE `date` >= '$date1' AND `date` <= '$date2'";
    $db->setQuery($query);
    $count_total_clicks = $db->loadResult();
    
    //get count of visible clicks
    $query = "SELECT COUNT(`id`) FROM #__heatmap WHERE `screen` = '$width' AND  `y` <= '$height' AND `date` >= '$date1' AND `date` <= '$date2'";
    $db->setQuery($query);
    $count_visible_clicks = $db->loadResult();
    
    //if total count is 0, set it to 1
    $count_total_clicks_devide = $count_total_clicks == 0 ? '1' : $count_total_clicks;
    $percent_vicible = ceil($count_visible_clicks * 100  / $count_total_clicks_devide);
    
    // Genetate clicks array
	$query = "SELECT * FROM #__heatmap WHERE `screen` = '$width' AND `date` >= '$date1' AND `date` <= '$date2'";
    $db->setQuery($query);
    $row = $db->loadAssocList();
    $clicks = array();
    foreach($row as $ckick_data) {
        $clicks[] = array($ckick_data['x'], $ckick_data['y']);
    }
    
    $heatmap->clicks = $clicks;
    $image_width = $width;
    $image_height = $height;

    $images = $heatmap->generate($image_width, $image_height);

    $rand = rand(100000,999999);
    if($images === false) {
        $response_image_content = 'error: '.$heatmap->error;
    } else {
        for($i = 0; $i < 1; $i++) {
            $response_image_content = '<img src=\"'. $images['absolutes'][$i] . '?rand=' . $rand . '\" width=\"' . $images['width'] . '\" height=\"' . $images['height'] . '\" alt=\"\" />';
        }
    }
    
    $clicks_count_content = 'Clicks : ' . $count_total_clicks . ' | Visible : ' .$percent_vicible . '%';
    
    //prints json object
    echo '["'.$response_image_content.'","'.$clicks_count_content.'"]';
    
    exit;
}
?>